package com.itheima.exception;


import com.itheima.common.R;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/*
      定义全局异常类处理
 */
@RestControllerAdvice
public class GlobalExceptionHandler {


        @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
        public R handleSQLIntegrityConstraintViolationException(SQLIntegrityConstraintViolationException e){
           //1.打印异常信息到控制台 [工作场景应该是打印在日志文件中]
            e.printStackTrace();
            //2.发短信，发邮件，通知运维或者开发人员

            //获取异常类的信息
            String message = e.getMessage();

            //判定
            if (message.contains("Duplicate entry")){
                String s = message.split(" ")[2];
                return R.error("账号："+s+", 已存在！");
            }
            //如果不是，也要告知页面未知错误
            return R.error("未知错误！");
        }

        @ExceptionHandler(CustomException.class)
        public R handleCustomException(CustomException e){
                return R.error(e.getMessage());

        }


}
